<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>书库</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
</head>
<body>
    <div class="container">
        <!-- 顶部导航栏 -->
        <div class="navbar">
            {% if not session.logged_in %}
                <a href="{{ url_for('login') }}" class="btn">未登录</a>
            {% else %}
            <img id="profile-picture" 
            src="{{ user.avatar_path }}?t={{ time() }}" 
            alt="Profile Picture" 
            class="profile-picture" 
            onclick="openUploadModal()">
            {% endif %}
            {% from 'macros.html' import search_form %}
            {{ search_form(request.args.get('q', '')) }}
        </div>

        <!-- 推荐区（2行） -->
        <div id="recommendationContainer" class="recommendation-container">
            <h2>个性推荐</h2>
            <button id="refreshRecommendBtn" class="btn">刷新推荐</button>
            <div id="recommendationList" class="recommendation-list">
                <!-- 这里由JS动态插入卡片 -->
            </div>
        </div>

        <!-- 主内容区（原书籍列表） -->
        <div class="content" id="book-container">
            {% for book in books %}
                <div class="card">
                    <a href="/book/{{ book.id }}">
                        <img src="{{ book.image }}" alt="{{ book.title }}">
                        <h3>{{ book.title }}</h3>
                        <div class="tags">
                            {% if book.tags %}
                                {% for tag in book.tags %}
                                    <span class="tag">{{ tag }}</span>
                                {% endfor %}
                            {% endif %}
                        </div>
                    </a>
                </div>
            {% endfor %}
        </div>
    </div>

    <!-- 底部导航栏 -->
    {% include 'footer.html' %}

    <script>
    document.addEventListener('DOMContentLoaded', () => {
        // 页面加载完自动拉取推荐
        fetchRecommendedBooks();

        // 点击“刷新”仅刷新推荐区
        document.getElementById('refreshRecommendBtn').addEventListener('click', () => {
            fetchRecommendedBooks();
        });
    });

    function fetchRecommendedBooks() {
        fetch('/api/recommend')
            .then(res => res.json())
            .then(data => {
                if (!data.success) {
                    console.error("获取推荐失败");
                    return;
                }
                const recommendationList = document.getElementById("recommendationList");
                // 清空
                recommendationList.innerHTML = "";

                // 1) 获取此时的列数
                //    通过 getComputedStyle() 读取 'grid-template-columns'
                const style = window.getComputedStyle(recommendationList);
                // 可能是形如 "300px 300px 300px" 的字符串
                const colCount = style.getPropertyValue('grid-template-columns')
                                      .split(' ').length;
                // 每行 colCount 个 -> 2 行 -> 最多 colCount * 2
                const maxItems = colCount * 2;

                // 2) 仅渲染前 maxItems 条（服务器可能返回多于 2行的书）
                const booksToShow = data.books.slice(0, maxItems);

                // 3) 插入卡片
                booksToShow.forEach(book => {
                    const card = document.createElement("div");
                    card.className = "card recommended-card";
                    card.innerHTML = `
                        <a href="/book/${book.id}">
                            <img src="${book.image}" alt="${book.title}">
                            <h3>${book.title}</h3>
                            <div class="tags">
                                ${book.tags.map(t => `<span class="tag">${t}</span>`).join('')}
                            </div>
                        </a>
                    `;
                    recommendationList.appendChild(card);
                });
            })
            .catch(err => {
                console.error("请求推荐接口出错:", err);
            });
    }
    </script>
</body>
</html>
